package com.example.exampleproject.base;

import android.content.Context;

import com.example.exampleproject.base.exception.ApiException;
import com.example.exampleproject.base.exception.BusinessException;

import java.lang.ref.WeakReference;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<T> {

    protected WeakReference<Context> context;

    private Disposable disposable;

    public BaseObserver(Context context) {
        this.context = new WeakReference<>(context);
    }

    protected abstract void onSuccess(T t);

    protected abstract void onBusinessException(Throwable e);

    protected abstract void onApiError(Throwable e);

    @Override
    public void onSubscribe(Disposable d) {
        this.disposable = d;
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
            try {
                if (e instanceof BusinessException) {
                    onBusinessException(e);
                } else if (e instanceof ApiException) {
                    onApiError(e);
                } else { // In case there is no use HandleErrTransformer before
                    ApiException apiException = ApiException.handleException(e);
                    onApiError(apiException);
                }
            } catch (Throwable ignored) {

            }
    }

    @Override
    public void onComplete() {

    }

    public Disposable attachDisposable() {
        return disposable;
    }
}
